package com.android.love.ui;

import java.io.File;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.love.MyApplication;
import com.android.love.R;
import com.android.love.callback.DataCallback;
import com.android.love.db.DatabaseUtil;
import com.android.love.net.NetWorkTask;
import com.android.love.net.UriHelper;
import com.android.love.receiver.ConnectivityReceiver;
import com.android.love.receiver.ConnectivityReceiver.OnNetworkAvailableListener;
import com.android.love.util.ActivityUtil;
import com.android.love.util.ApkUtil;
import com.android.love.util.CacheUtils;
import com.android.love.util.Constant;
import com.android.love.util.DeviceUtil;
import com.android.love.util.FileUtil;
import com.android.love.util.Sputil;
import com.android.love.view.BadgeView;
import com.android.love.view.PopupHelper;
import com.android.love.vo.Goods;
import com.android.love.vo.MyRequest;
import com.github.kevinsawicki.wishlist.ViewUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;

public abstract class BasePageActivity extends BaseActivity implements
		DataCallback, OnNetworkAvailableListener, OnClickListener, Constant {
	protected static final String TAG = "BasePageActivity";
	protected MyApplication mApplication;
	protected Sputil sp;
	protected ImageLoader loader;
	protected Context context;
	protected Dialog dialog;
	protected BaseHandler baseHandler;
	protected ConnectivityReceiver connectivityReceiver;
	protected NetWorkTask task;
	protected LayoutInflater inflater;
	/** 推荐 **/
	private ImageView iv_recommend;
	/** 分类 **/
	private ImageView iv_class;
	/** 美秀 **/
	private ImageView iv_meixiu;
	/** 购物车 **/
	private ImageView iv_shopCar;
	/** 个人中心 **/
	private ImageView iv_setting;

	// protected MyHandler mHandler;
	protected int user_id;
	protected String sig;
	// private LoadingDialog mLoadingDialog;
	private BadgeView cart_badge;
	private BadgeView order_badge;
	private TextView tv_recommend;
	private TextView tv_class;
	private TextView tv_meixiu;
	private TextView tv_shopCar;
	private TextView tv_setting;
	private LinearLayout ll_class;
	private LinearLayout ll_recommend;
	private LinearLayout ll_meixiu;
	private LinearLayout ll_shopcar;
	private LinearLayout ll_setting;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		UmengUpdateAgent.update(this);
		UmengUpdateAgent.setUpdateListener(null);
		ActivityUtil.setScreenVertical(this);
		ActivityUtil.hideTitleBar(this);
		loader = ImageLoader.getInstance();
		mApplication = MyApplication.getInstance();
		mApplication.addActivity(this);
		// mHandler = MyHandler.getInstance();
		sp = new Sputil(mApplication, PER_FILE);
		user_id = sp.getValue(USER_ID, 0);
		sig = sp.getValue(SIG, "");
		inflater = LayoutInflater.from(context);
		baseHandler = new BaseHandler(context);
		if (connectivityReceiver == null)
			connectivityReceiver = new ConnectivityReceiver(context);
		connectivityReceiver.bind(context);
		// if (mLoadingDialog == null)
		// mLoadingDialog = new LoadingDialog(context);
		
		
		
		Sputil sp=new Sputil(context);
		String cid=sp.getValue("cid", null);
		if(cid!=null){
			BetterActivityHelper.newMessageDialog(context, "获取ClientID", cid+"", android.R.drawable.ic_dialog_info).show();
		}
//		sp.setValue("cid", cid);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		if (loadBottomTab()) {
			setBottomTab();
			selectedBottomTab(mApplication.getDefaultIndex());
			updateBottomCart();
			updateBottomOrder();
		}
		connectivityReceiver.bind(context);
	}

	/**
	 * 更新底部栏购物车提醒
	 */
	protected void updateBottomCart() {
		List<Goods> lists = DatabaseUtil.getInstance(context).queryCart();
		if (lists != null && lists.size() > 0) {
			if (cart_badge == null) {
				cart_badge = new BadgeView(this, findViewById(R.id.iv_shopCar));
			}
			cart_badge.setText(lists.size() + "");
			cart_badge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
			// badge.setBackgroundResource(R.color.purple);
			cart_badge.setBadgeBackgroundColor(getResources().getColor(
					R.color.pink));
			cart_badge.setTextColor(getResources().getColor(R.color.white));
			cart_badge.show(true);
		} else {
			if (cart_badge != null)
				cart_badge.hide();
		}
	}

	/**
	 * 更新底部栏订单提醒
	 */
	protected void updateBottomOrder() {
		int order_num = sp.getValue(ORDER_NUM, 0);
		if (order_num > 0) {
			if (order_badge == null) {
				order_badge = new BadgeView(this, findViewById(R.id.iv_setting));
			}
			order_badge.setText(order_num + "");
			order_badge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
			// badge.setBackgroundResource(R.color.purple);
			order_badge.setBadgeBackgroundColor(getResources().getColor(
					R.color.pink));
			order_badge.setTextColor(getResources().getColor(R.color.white));
			order_badge.show(true);
		} else {
			if (order_badge != null)
				order_badge.hide();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		connectivityReceiver.unbind(context);
	}

	protected BasePageActivity show(final View view) {
		ViewUtils.setGone(view, false);
		return this;
	}

	protected BasePageActivity hide(final View view) {
		ViewUtils.setGone(view, true);
		return this;
	}

	@Override
	public void onNetworkAvailable() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNetworkUnavailable() {
		// TODO Auto-generated method stub

	}

	/**
	 * 
	 * @author adison
	 * 
	 */
	public class BaseHandler extends Handler {

		private Context context;

		public BaseHandler(Context context) {
			this.context = context;
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {

			case LOADING:
				// startWationDialog();
				View view = LayoutInflater.from(context).inflate(
						R.layout.waiting, null);
				dialog = newCustomDialog(R.style.waiting, view);
				dialog.show();
				break;
			case LOADING_DISMISS:
				// closeWationDialog();
				if (dialog != null) {
					dialog.cancel();
					dialog = null;
				}
				break;
			case GET_DATA_FAIL:

				break;

			}

		}
	}

	/**
	 * 从服务器或者本地数据库上获取数据
	 * 
	 * @param context
	 * @param req
	 * @param tag
	 * @param obj
	 */
	public void getDataFromTask(Context context, int tag, MyRequest req,
			Object obj, boolean show, boolean get) {
		task = new NetWorkTask(context, show, get, baseHandler);
		task.execute(context, tag, req, obj);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (dialog != null) {
			dialog.cancel();
			dialog = null;
		}
	}

	/**
	 * 是否加载底部tab
	 * 
	 * @return
	 */
	protected Boolean loadBottomTab() {
		return true;
	}

	/**
	 * 
	 */
	private void setBottomTab() {
		ll_class = (LinearLayout) findViewById(R.id.ll_class);
		ll_recommend = (LinearLayout) findViewById(R.id.ll_recommend);
		ll_meixiu = (LinearLayout) findViewById(R.id.ll_meixiu);
		ll_shopcar = (LinearLayout) findViewById(R.id.ll_shopcar);
		ll_setting = (LinearLayout) findViewById(R.id.ll_setting);
		this.iv_recommend = (ImageView) findViewById(R.id.iv_recommend);
		this.iv_class = (ImageView) findViewById(R.id.iv_class);
		this.iv_meixiu = (ImageView) findViewById(R.id.iv_meixiu);
		this.iv_shopCar = (ImageView) findViewById(R.id.iv_shopCar);
		this.iv_setting = (ImageView) findViewById(R.id.iv_setting);
		this.tv_recommend = (TextView) findViewById(R.id.tv_recommend);
		this.tv_class = (TextView) findViewById(R.id.tv_class);
		this.tv_meixiu = (TextView) findViewById(R.id.tv_meixiu);
		this.tv_shopCar = (TextView) findViewById(R.id.tv_shopCar);
		this.tv_setting = (TextView) findViewById(R.id.tv_setting);
		this.ll_recommend.setOnClickListener(this);
		this.ll_class.setOnClickListener(this);
		this.ll_meixiu.setOnClickListener(this);
		this.ll_setting.setOnClickListener(this);
		this.ll_shopcar.setOnClickListener(this);
	}

	/**
	 * tab条图片切换
	 * 
	 * @param paramViewId
	 * @param paramViewId
	 * @param paramViewId
	 */
	protected void selectedBottomTab(int paramViewId) {
		this.iv_recommend.setImageResource(R.drawable.tuijian);
		this.iv_class.setImageResource(R.drawable.feilei);
		this.iv_meixiu.setImageResource(R.drawable.meixiu);
		this.iv_shopCar.setImageResource(R.drawable.gouwuche);
		this.iv_setting.setImageResource(R.drawable.gerenzhongxin);
		this.tv_recommend.setTextColor(getResources().getColor(
				R.color.black_text));
		this.tv_class.setTextColor(getResources().getColor(R.color.black_text));
		this.tv_meixiu
				.setTextColor(getResources().getColor(R.color.black_text));
		this.tv_shopCar.setTextColor(getResources()
				.getColor(R.color.black_text));
		this.tv_setting.setTextColor(getResources()
				.getColor(R.color.black_text));
		switch (paramViewId) {
		case HOME:
			this.iv_recommend.setImageResource(R.drawable.tuijian_on);
			this.tv_recommend.setTextColor(getResources()
					.getColor(R.color.pink));
			break;
		case CLASSIFY:
			this.iv_class.setImageResource(R.drawable.feilei_on);
			this.tv_class.setTextColor(getResources().getColor(R.color.pink));
			break;
		case MEIXIU:
			this.iv_meixiu.setImageResource(R.drawable.meixiu_on);
			this.tv_meixiu.setTextColor(getResources().getColor(R.color.pink));
			break;
		case SHOPCAR:
			this.iv_shopCar.setImageResource(R.drawable.gouwuche_on);
			this.tv_shopCar.setTextColor(getResources().getColor(R.color.pink));
			break;
		case SETTING:
			this.iv_setting.setImageResource(R.drawable.gerenzhongxin_on);
			this.tv_setting.setTextColor(getResources().getColor(R.color.pink));
			break;
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		switch (v.getId()) {
		case R.id.ll_recommend: {
			intent.setClass(this, HomeActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			overridePendingTransition(0, 0);
		}
			break;
		case R.id.ll_class: {
			intent.setClass(this, ClasssifyActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			Log.e("TAB2", "Classify");
			startActivity(intent);
			overridePendingTransition(0, 0);
		}
			break;
		case R.id.ll_meixiu: {
			intent.setClass(this, MeixiuActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			Log.e("TAB3", "Search");
			startActivity(intent);
			overridePendingTransition(0, 0);
		}
			break;
		case R.id.ll_shopcar: {
			intent.setClass(this, CartActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			// intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			Log.e("TAB4", "ShoppingCar");
			startActivity(intent);
			overridePendingTransition(0, 0);
		}
			break;
		case R.id.ll_setting: {
			intent.setClass(this, SettingActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			overridePendingTransition(0, 0);
		}
			break;

		default:
			break;
		}
	}

	/**
	 * 设置监听
	 */
	protected void setListener() {
	};

	/**
	 * 处理一般逻辑
	 */
	protected void process() {
	};

	/**
	 * 获取数据（联网或者取本地数据库）
	 */
	protected void getData() {
	};

	@Override
	public void handle(int tag, Object object) {
		// Message msg = new Message();
		// msg.what = LOADING_DISMISS;
		// baseHandler.sendMessage(msg);
		baseHandler.sendEmptyMessage(LOADING_DISMISS);

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& keyCode == KeyEvent.KEYCODE_BACK) {
			newYesNoDialog(R.string.exit_title, R.string.exit_message,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (which == DialogInterface.BUTTON_POSITIVE) {
							    File appCacheDir=CacheUtils.getUserCache(context, "/love");
							    FileUtil.deleteDirectory(appCacheDir);
								mApplication.exit();
							}

						}
					}).show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 显示选择类别的popupWindow
	 */
	protected void showPopupWindow(View anchorView, int type) {
		final PopupWindow window = PopupHelper.newBasicPopupWindow(this);
		// 得到popupWindow的显示布局
		View view = LayoutInflater.from(this)
				.inflate(R.layout.type_popup, null);
		window.setContentView(view);
		LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
		if(type==1){
			ll_popup.setBackgroundResource(R.drawable.popup_bg_right);
		}
		if(type==2){
			ll_popup.setBackgroundResource(R.drawable.popup_bg_left);
		}
		if (type==3) {
			ll_popup.setBackgroundResource(R.drawable.popup_bg_down);
		}
		int totalHeight = getWindowManager().getDefaultDisplay().getHeight();
		int[] location = new int[2];
		anchorView.getLocationOnScreen(location);
		if (location[1] < (totalHeight / 2.0)) {
			// top half of screen
			Log.i("PopupHelper", "1-----");
			window.setAnimationStyle(R.style.Animations_PopDownMenuRight);
			window.showAsDropDown(anchorView);
		} else { // bottom half
			Log.i("PopupHelper", "2-----");
			PopupHelper.showLikeQuickAction(window, view, anchorView,
					getWindowManager(), 0, 0);
		}
		view.findViewById(R.id.rl_qq).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (ApkUtil.isPackageExists(context, "com.tencent.mobileqq")) {
					ApkUtil.launch(BasePageActivity.this,
							"com.tencent.mobileqq");
					ClipboardManager cmd = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
					cmd.setText("501766");
					ActivityUtil.show(BasePageActivity.this, "已经复制了QQ号：501766");
				} else {
					ActivityUtil.show(BasePageActivity.this, "没有安装QQ客户端");

				}

				window.dismiss();
			}
		});
		view.findViewById(R.id.rl_wx).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// if (ApkUtil.isPackageExists(context, "com.tencent.mobileqq"))
				// {
				// ApkUtil.launch(BasePageActivity.this,
				// "com.tencent.mobileqq");
				ClipboardManager cmd = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
				cmd.setText("aiaige99");
				ActivityUtil.show(BasePageActivity.this, "已复制爱爱微信号，请直接打开微信客户端，搜索添加“aiaige99");
				// } else {
				// ActivityUtil.show(BasePageActivity.this, "没有安装QQ客户端");
				//
				// }
				// Uri uri = Uri
				// .parse("http://weixin.qq.com/r/gHSMg7zEE4Jsh63gnyGk");
				// context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
				 window.dismiss();
			}
		});
		view.findViewById(R.id.rl_phone).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						DeviceUtil.dial("123456", context);
						window.dismiss();
					}
				});
	}

}
